package com.hlx.herostory.cmdhandler;

import com.hlx.herostory.model.User;
import com.hlx.herostory.model.UserManager;
import com.hlx.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;

public class WhoElseIsHereCmdHandler implements ICmdHandler<GameMsgProtocol.WhoElseIsHereCmd> {

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.WhoElseIsHereCmd msg) {
        GameMsgProtocol.WhoElseIsHereResult.Builder resultBuilder = GameMsgProtocol.WhoElseIsHereResult.newBuilder();

        for (User currUser : UserManager.listUser()) {
            if (null == currUser) {
                continue;
            }

            GameMsgProtocol.WhoElseIsHereResult.UserInfo.Builder userInfoBuilder
                    = GameMsgProtocol.WhoElseIsHereResult.UserInfo.newBuilder();
            userInfoBuilder.setUserId(currUser.userId);
            userInfoBuilder.setHeroAvatar(currUser.heroAvatar);


            GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.Builder moveStateBuilder
                    = GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.newBuilder();

            moveStateBuilder.setFromPosX(currUser.moveState.fromPosX);
            moveStateBuilder.setFromPosY(currUser.moveState.fromPosY);
            moveStateBuilder.setStartTime(currUser.moveState.startTime);
            moveStateBuilder.setToPosX(currUser.moveState.toPosX);
            moveStateBuilder.setToPosY(currUser.moveState.toPosY);

            GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState moveState = moveStateBuilder.build();
            userInfoBuilder.setMoveState(moveState);

            resultBuilder.addUserInfo(userInfoBuilder);
        }

        GameMsgProtocol.WhoElseIsHereResult newResult = resultBuilder.build();
        ctx.writeAndFlush(newResult);
    }
}
